#!/bin/bash

# 环境管理脚本

show_help() {
    echo "🌍 环境管理脚本"
    echo ""
    echo "用法: $0 [命令] [环境]"
    echo ""
    echo "命令:"
    echo "  set <env>     设置环境 (local|test|staging|prod)"
    echo "  show          显示当前环境信息"
    echo "  list          列出所有可用环境"
    echo "  validate      验证当前环境配置"
    echo "  help          显示此帮助信息"
    echo ""
    echo "环境:"
    echo "  local         本地开发环境"
    echo "  test          测试环境"
    echo "  staging       预发布环境"
    echo "  prod          生产环境"
    echo ""
    echo "示例:"
    echo "  $0 set local      # 切换到本地开发环境"
    echo "  $0 set prod       # 切换到生产环境"
    echo "  $0 show           # 显示当前环境"
}

set_environment() {
    local env=$1
    local env_file=""
    
    case $env in
        local|dev|development)
            env_file="config/env.local.json"
            export NODE_ENV=development
            ;;
        test)
            env_file="config/env.test.json"
            export NODE_ENV=test
            ;;
        staging|stage)
            env_file="config/env.staging.json"
            export NODE_ENV=staging
            ;;
        prod|production)
            env_file="config/env.prod.json"
            export NODE_ENV=production
            ;;
        *)
            echo "❌ 无效的环境: $env"
            echo "可用环境: local, test, staging, prod"
            exit 1
            ;;
    esac
    
    if [ ! -f "$env_file" ]; then
        echo "❌ 环境配置文件不存在: $env_file"
        exit 1
    fi
    
    # 验证 JSON 格式
    if ! jq empty "$env_file" 2>/dev/null; then
        echo "❌ JSON 格式验证失败: $env_file"
        exit 1
    fi
    
    echo "✅ 已切换到 $env 环境"
    echo "📄 使用配置文件: $env_file"
    echo "🔧 环境变量: NODE_ENV=$NODE_ENV"
    
    # 显示环境信息
    show_environment
}

show_environment() {
    local node_env="${NODE_ENV:-development}"
    local config_file="config/env.${node_env}.json"
    
    if [ ! -f "$config_file" ]; then
        echo "❌ 环境配置文件不存在: $config_file"
        return 1
    fi
    
    # 使用 jq 解析 JSON 配置
    if command -v jq >/dev/null 2>&1; then
        local app_port=$(jq -r '.APP_PORT // 3000' "$config_file")
        local db_host=$(jq -r '.DB_HOST // "localhost"' "$config_file")
        local redis_host=$(jq -r '.REDIS_HOST // "localhost"' "$config_file")
        local db_port=$(jq -r '.DB_PORT // 3306' "$config_file")
        local redis_port=$(jq -r '.REDIS_PORT // 6379' "$config_file")
        
        echo ""
        echo "🌍 当前环境信息:"
        echo "  环境: $node_env"
        echo "  配置文件: $config_file"
        echo "  端口: $app_port"
        echo "  数据库: $db_host:$db_port"
        echo "  Redis: $redis_host:$redis_port"
        echo ""
    else
        echo ""
        echo "🌍 当前环境信息:"
        echo "  环境: $node_env"
        echo "  配置文件: $config_file"
        echo "  💡 安装 jq 以获得更详细的配置信息"
        echo ""
    fi
}

list_environments() {
    echo "🌍 可用环境:"
    echo ""
    
    for env_file in config/env.*.json; do
        if [ -f "$env_file" ]; then
            local env_name=${env_file#config/env.}
            env_name=${env_name%.json}
            local description=""
            
            case $env_name in
                local) description="本地开发环境" ;;
                test) description="测试环境" ;;
                staging) description="预发布环境" ;;
                prod) description="生产环境" ;;
                *) description="自定义环境" ;;
            esac
            
            # 使用 jq 获取 NODE_ENV 值
            if command -v jq >/dev/null 2>&1; then
                local node_env=$(jq -r '.NODE_ENV // "unknown"' "$env_file")
                echo "  $env_name ($node_env) - $description"
            else
                echo "  $env_name - $description"
            fi
        fi
    done
    echo ""
}

validate_environment() {
    local node_env="${NODE_ENV:-development}"
    local config_file="config/env.${node_env}.json"
    
    if [ ! -f "$config_file" ]; then
        echo "❌ 环境配置文件不存在: $config_file"
        return 1
    fi
    
    echo "🔍 验证环境配置: $config_file"
    
    # 验证 JSON 格式
    if ! jq empty "$config_file" 2>/dev/null; then
        echo "❌ JSON 格式验证失败"
        return 1
    fi
    
    # 必需的环境变量
    local required_vars=("NODE_ENV" "DB_HOST" "DB_USERNAME" "DB_PASSWORD" "DB_DATABASE" "REDIS_HOST" "JWT_SECRET")
    local missing_vars=()
    
    for var in "${required_vars[@]}"; do
        if ! jq -e ".$var" "$config_file" >/dev/null 2>&1; then
            missing_vars+=("$var")
        fi
    done
    
    if [ ${#missing_vars[@]} -eq 0 ]; then
        echo "✅ 环境配置验证通过"
        show_environment
    else
        echo "❌ 缺少必需的环境变量:"
        for var in "${missing_vars[@]}"; do
            echo "  - $var"
        done
        return 1
    fi
}

# 主逻辑
case "${1:-help}" in
    set)
        if [ -z "$2" ]; then
            echo "❌ 请指定环境名称"
            echo "用法: $0 set <环境>"
            exit 1
        fi
        set_environment "$2"
        ;;
    show|current)
        show_environment
        ;;
    list|ls)
        list_environments
        ;;
    validate|check)
        validate_environment
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo "❌ 未知命令: $1"
        show_help
        exit 1
        ;;
esac
